﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Reflection;
using System.Threading;

namespace AppService {
    static class Program {
        static void Main(string[] args) {
            System.Threading.Thread.GetDomain().UnhandledException += new UnhandledExceptionEventHandler(Program_UnhandledException);

            var srv = new Service();
            if (args != null && args.Length > 0 && args[0] == "debug") {
                srv.ManualStart();
                Console.WriteLine("Press Enter to Stop");
                Console.ReadLine();
                srv.Stop();

            } else {
                try {
                    ServiceBase.Run(srv);
                } catch (Exception ex) {
                    System.Diagnostics.EventLog.WriteEntry("AppService", "Unhandled Exception: " + ex.ToString(), System.Diagnostics.EventLogEntryType.Error, 400);
                    throw ex;
                }
            }
        }

        public static void Program_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
            System.Diagnostics.EventLog.WriteEntry("AppService", "Program_UnhandledException: " + e.ExceptionObject.ToString(), System.Diagnostics.EventLogEntryType.Error, 300);
        }

        public static void Try(Action action, int times, int timeoutBetweenTries) {
            ManualResetEvent mre = new ManualResetEvent(false);
            int n = 0;
            while(true){
                try {
                    n++;
                    action();
                    return;

                } catch (Exception ex) {
                    System.Diagnostics.EventLog.WriteEntry("AppService", "Program_TryException: " + ex.ToString(), System.Diagnostics.EventLogEntryType.Error, 200);
                    if (n >= 10) throw ex;
                    else mre.WaitOne(timeoutBetweenTries);
                }
            } 
        }
    }

}
